package com.cs.common.json;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;

public class JsonUtil {
    private static ObjectMapper objectMapper = new ObjectMapper();

    static {
    	// 设定使用驼峰方式 即 user_name -> userName
    	objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
    	// 设定对象有不存在的字段不会报错
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }
    
    /**
     * 转换为json字符串
     */
    public static String toJson(Object object) throws JsonProcessingException {
        return objectMapper.writeValueAsString(object);
    }

    /**
     * json转对象
     */
    public static Object fromJson(String string, Class classType) throws JsonProcessingException {
        return objectMapper.readValue(string, classType);
    }

    /**
     * json转通用类型
     */
    public static Object fromJson(String string, TypeReference typeReference) throws JsonProcessingException {
        return objectMapper.readValue(string, typeReference);
    }

}
